<template>
  <div class="source">
    <div>
      <el-form :model="goodInfo" :rules="addInfoRules" ref="goodInfo" label-width="110px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="名称：" prop="goodsName">
                <el-input v-model="goodInfo.goodsName" placeholder="请输入商品名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item  label="单位：" prop="goodsUnit">
              <el-input v-model="goodInfo.goodsUnit" placeholder="请输入商品单位"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item  label="关键字：" prop="keywords">
              <el-input v-model="goodInfo.keywords" placeholder="请输入商品关键字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item  label="数量：" prop="goodsNumber">
              <el-input v-model="goodInfo.goodsNumber" placeholder="请输入商品数量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item  label="报警数量：" prop="warnNumber">
              <el-input v-model="goodInfo.warnNumber" placeholder="请输入库存报警数量"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item  label="重量：" prop="goodsWeight">
              <el-input v-model="goodInfo.goodsWeight" placeholder="请输入商品重量"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item  label="销售价：" prop="shopPrice">
              <el-input v-model="goodInfo.shopPrice" placeholder="请输入销售价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item  label="成本价：" prop="costPrice">
              <el-input v-model="goodInfo.costPrice" placeholder="请输入成本价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item  label="市场价：" prop="marketPrice">
              <el-input v-model="goodInfo.marketPrice" placeholder="请输入市场价"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item  label="简短描述：" prop="goodsBrief">
              <el-input v-model="goodInfo.goodsBrief" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入商品简短描述(小于50字)"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item  label="详细描述：" prop="goodsDesc">
              <el-input v-model="goodInfo.goodsDesc" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入商品详细描述（小于100字）"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item  label="备注：" prop="sellerNote">
              <el-input v-model="goodInfo.sellerNote" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="商家备注（仅商家可见；小于100字）"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-form-item label="展示图：" :required="true">
              <el-upload
                class="upload-demo"
                ref="uploadImgThumb"
                action="http://localhost:8888/shopGoods/data/uploadFile"
                :headers="uploadHeaders"
                list-type="picture-card"
                :limit="1"
                :before-upload="beforeUploadImgThumb"
                :on-success="successImgThumb"
                :on-remove="removeImgThumb">
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" slot="tip">商品列表展示图（只能选择一张图）</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="详情轮播图：" :required="true">
              <el-upload
                class="upload-demo"
                ref="uploadImgList"
                action="http://localhost:8888/shopGoods/data/uploadFile"
                :headers="uploadHeaders"
                list-type="picture-card"
                :limit="10"
                :on-exceed="exceedImgList"
                :before-upload="beforeUploadImgList"
                :on-success="successImgList"
                :on-remove="removeImgList">
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" slot="tip">详情页轮播图（最多不超过十张图）</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="resetForm('goodInfo')">重置<i class="el-icon-close el-icon--right"></i></el-button>
          <el-button type="primary" @click="submitForm('goodInfo')">提交审核<i class="el-icon-upload2 el-icon--right"></i></el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import 'element-ui/lib/theme-chalk/display.css'
  import goodsApi from '@/api/backstage/goods'
  import { getToken } from '@/utils/auth'
  export default {
    name: 'Goods_addGoods',
    data() {
      const validateGoodsName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        }
        callback();
      }
      const validateGoodsUnit = (rule, value, callback) => {
        callback();
      }
      const validateKeywords = (rule, value, callback) => {
        callback();
      }
      const validateGoodsWeight = (rule, value, callback) => {
        callback();
      }
      const validateGoodsNumber = (rule, value, callback) => {
        callback();
      }
      const validateWarnNumber = (rule, value, callback) => {
        callback();
      }
      const validateShopPrice = (rule, value, callback) => {
        callback();
      }
      const validateCostPrice = (rule, value, callback) => {
        callback();
      }
      const validateMarketPrice = (rule, value, callback) => {
        callback();
      }
      const validateGoodsBrief = (rule, value, callback) => {
        callback();
      }
      const validateGoodsDesc = (rule, value, callback) => {
        callback();
      }
      const validateSellerNote = (rule, value, callback) => {
        callback();
      }
      return {
        uploadHeaders: {
          'user-token':getToken()
        },
        imgInfos:[],
        imgUidThumb:[],
        imgUidList:[],
        goodInfo: {
          goodsName: '',
          goodsUnit: '',
          keywords: '',
          goodsWeight: '',
          goodsNumber: '',
          warnNumber: '',
          shopPrice: '',
          costPrice: '',
          marketPrice: '',
          goodsBrief: '',
          goodsDesc: '',
          sellerNote: '',
        },
        addInfoRules: {
          goodsName: [{required: true, trigger: 'blur', validator: validateGoodsName}],
          goodsUnit: [{required: true, trigger: 'blur', validator: validateGoodsUnit}],
          keywords: [{required: true, trigger: 'blur', validator: validateKeywords}],
          goodsWeight: [{required: true, trigger: 'blur', validator: validateGoodsWeight}],
          goodsNumber: [{required: true, trigger: 'blur', validator: validateGoodsNumber}],
          warnNumber: [{required: true, trigger: 'blur', validator: validateWarnNumber}],
          shopPrice: [{required: true, trigger: 'blur', validator: validateShopPrice}],
          costPrice: [{required: true, trigger: 'blur', validator: validateCostPrice}],
          marketPrice: [{required: true, trigger: 'blur', validator: validateMarketPrice}],
          goodsBrief: [{required: true, trigger: 'blur', validator: validateGoodsBrief}],
          goodsDesc: [{required: true, trigger: 'blur', validator: validateGoodsDesc}],
          sellerNote: [{required: true, trigger: 'blur', validator: validateSellerNote}]
        }
      }
    },
    methods: {
      resetForm(formName){
        this.$refs[formName].resetFields()
        this.$refs.uploadImgThumb.clearFiles()
        this.$refs.uploadImgList.clearFiles()
        this.imgUidThumb = []
        this.imgUidList = []
        this.imgInfos = []
      },
      submitForm(goodInfoOfSubmit) {
        this.$refs[goodInfoOfSubmit].validate(valid => {
          if(valid) {
            if (this.imgUidThumb == null || this.imgUidThumb.length==0){
              this.$message.error("展示图不能为空！")
              return false
            }
            if (this.imgUidList == null || this.imgUidList.length==0){
              this.$message.error("详情轮播图不能为空！")
              return false
            }
            this.imgInfos = []
            this.imgInfos.push({
              url: this.imgUidThumb[0].url,
              type: 1,
              photoSort: 10
            })
            for (let i = 0; i < this.imgUidList.length; i++){
              this.imgInfos.push({
                url: this.imgUidList[i].url,
                type: 2,
                photoSort: (i + 1) * 10
              })
            }
            goodsApi.saveGoods(JSON.parse(JSON.stringify(this.goodInfo)), this.imgInfos).then(res => {
              console.log(res.data)
            })
          } else {
            this.$message.error("提交失败！")
            return false
          }
        })
      },
      //第二页开始
      beforeUploadImgThumb(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt1M = file.size / 1024 / 1024 < 1;
        this.beforeUploadImgRule(isJPG,"JPG",isLt1M,"1MB")
        return isJPG && isLt1M;
      },
      successImgThumb(response, file, fileList){
        this.imgUidThumb.push({
          uid: file.uid,
          name: file.name,
          url: response.data[file.name]
        })
      },
      removeImgThumb(file, fileList){
        //文件列表移除时，移除
        let imgUidThumb = this.imgUidThumb
        for(let i = 0; i < imgUidThumb.length; i++){
          if (imgUidThumb[i].uid==file.uid){
            this.imgUidThumb.splice(i,1)
            break
          }
        }
      },//end
      exceedImgList(file, fileList){
        this.$message.warning('当前限制选择10个文件，你超出了可选择数量')
      },
      beforeUploadImgList(file){
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        this.beforeUploadImgRule(isJPG,"JPG",isLt2M,"2MB")
        return isJPG && isLt2M;
      },
      successImgList(response, file, fileList){
        let imgUid = {
          uid: file.uid,
          name: file.name,
          url: response.data[file.name]
        }
        this.imgUidList.push(imgUid)
      },
      removeImgList(file, fileList){
        let imgUidList = this.imgUidList
        for(let i = 0; i < imgUidList.length; i++){
          if (imgUidList[i].uid==file.uid){
            this.imgUidList.splice(i,1)
            break
          }
        }
      },//end

      beforeUploadImgRule(isFormat,formatValue, isLt, ltValue){
        // 图片格式、大小规则检验
        if (!isFormat) {
          this.$message.error('上传图片只能是 '+formatValue+' 格式!');
        }
        if (!isLt) {
          this.$message.error('上传图片大小不能超过 '+ltValue+'!');
        }
      }
    }

  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .source{
    width: 100%;
    min-width: 800px;
  }
  .el-row {
    margin-bottom: 20px;
  }
  .li-input-title {
    text-align: right;
    line-height: 40px;
    width: 100px;
    float: left;
  }
</style>
